<template>
  <div>
    <header style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <h1>电路名：{{ circuitName }}</h1>
        <el-button
          style="margin-left: 20px; margin-top: -3px"
          @click="showDialog = true"
          >修改
        </el-button>
      </div>
      <div>
        <el-button
          type="primary"
          style="
            margin-right: 20px;
            margin-top: -3px;
            height: 35px;
            font-size: 18px;
            background-color: #595959;
          "
          @click="back"
          >关闭该页面
        </el-button>
      </div>
    </header>
    <main
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
    >
      <div
        style="
          display: flex;
          justify-content: center;
          width: 100%;
          align-items: center;
        "
      >
        <span>请输入文件路径：</span>
        <el-input
          v-model="fileDirectoryPath"
          style="width: 50%"
          placeholder="请输入服务器文件路径"
        ></el-input>
        <el-button
          @click="readFileDirectoryPath"
          type="primary"
          style="background-color: #003f82; margin-left: 10px"
          >读取内容</el-button
        >
      </div>
      <el-card
        style="
          width: 80%;
          height: 80%;
          display: flex;
          justify-content: center;
          margin-top: 10px;
        "
      >
        <el-form
          :model="configForm"
          :rules="rules"
          label-width="170px"
          style="display: flex; flex-direction: column; font-size: 30px"
          size="large"
        >
          <el-form-item
            v-for="(item, index) in formItems"
            :key="index"
            :label="item.label"
            :prop="item.prop"
            style="margin-bottom: 10px"
          >
            <el-select
              v-model="configForm[item.prop]"
              placeholder="请选择文件"
              class="inputStyles"
              @change="handleSelectChange(item.prop, $event)"
            >
              <el-option
                v-for="(file, index) in filesNameLs"
                :key="index"
                :label="file"
                :value="file"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <footer>
          <el-button
            type="primary"
            @click="uploadConfig"
            style="
              margin-top: -30px;
              font-size: 20px;
              height: 35px;
              background-color: #003f82;
            "
            >上传配置
          </el-button>
        </footer>
      </el-card>
    </main>
    <!-- 弹窗 -->
    <el-dialog title="修改电路名" v-model="showDialog" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="原电路名">
          <el-input v-model="form.old_circuit_diagram_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新电路名">
          <el-input v-model="form.new_circuit_diagram_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    {{ filesNameLs.value }}
  </div>
</template>

<script setup name="电路配置">
import { ref, onMounted,watchEffect } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  reCircuitName,
  huada_config_upload,
  huada_config_upload1,
  getUploadFiles,
} from "@/server/circuit";
import router from "@/router/index.js";

const route = useRoute();
const circuitName = ref("...");
const configFile = ref({
  fileNameSp: "",
  fileNameMengSp: "",
});

const back = () => {
  router.back();
};

/*-------------------------------------------------------------------------*/
const reqData = ref(null);
const fileDirectoryPath = ref(
  "/home/hzb/huaxing/GOA_web_project/goa_LCD_opt/web_simulation_files/li5_65SNB"
);
const readFileDirectoryPath = async () => {
  try {
    reqData.value = {};
    reqData.value.电路名称 = route.params.circuitName;
    reqData.value.服务器配置路径 = fileDirectoryPath.value;
    console.log("reqData:", reqData);
    const response = await huada_config_upload1(reqData.value);
    filesNameLs.value=response.file_ls
    console.log("filesNameLs.value:", filesNameLs.value);
  } catch (e) {
    console.error("e:", e);
  }
};
const filesNameLs=ref([]);


const handleSelectChange = (prop,event)=>{
    console.log("prop:",prop);
    console.log("event:",event)
    console.log("configFrom:",configForm.value)
}





const formItems = ref([
  { label: "默认sp文件:", prop: "property1" },
  { label: "电路结构netlist文件:", prop: "property2" },
  { label: "温度mod默认文件:", prop: "property3" },
  { label: "AI_fixed文件:", prop: "property4" },
  { label: "AI_change文件:", prop: "property5" },
  { label: "温度mod文件1:", prop: "property6" },
  { label: "温度mod文件2:", prop: "property7" },
  { label: "ra文件:", prop: "property8" },
  { label: "蒙特卡洛默认sp文件:", prop: "property9" },
  { label: "蒙特卡洛AI_fixed文件:", prop: "property10" },
  { label: "蒙特卡洛AI_change文件:", prop: "property11" },
  { label: "蒙特卡洛ra文件:", prop: "property12" },
]);
// watchEffect(() => {
//   console.log("filesNameLs updated:", filesNameLs.value);
// });
/*---------------------------以下代码将在后期进行删除------------------------------*/

const getUploadFile = async () => {
  try {
    const response = await getUploadFiles({circuit_diagram_name: route.params.circuitName})
    console.log(response)
    const fileMap = {
      AI_change文件_n: "AI_change文件",
      AI_fixed文件_n: "AI_fixed文件",
      温度mod默认文件_n: "温度mod默认文件",
      电路结构netlist文件_n: "电路结构netlist文件",
      蒙特卡洛AI_change文件_n: "蒙特卡洛AI_change文件",
      蒙特卡洛AI_fixed文件_n: "蒙特卡洛AI_fixed文件",
      蒙特卡洛sp文件_n: "蒙特卡洛sp文件",
      默认sp文件_n: "默认sp文件",
      温度mod文件1_n: "温度mod文件1",
      温度mod文件2_n: "温度mod文件2",
      ra文件_n: "ra文件",
      蒙特卡洛ra文件_n: "蒙特卡洛ra文件",
    };
    for (const [key, value] of Object.entries(response)) {
      if (key.endsWith("_n")) {
        const fileName = key;
        const _nFileName = value;
        const fileContentKey = key.replace("_n", "_c");
        if (response.hasOwnProperty(fileContentKey)) {
          const fileContent = response[fileContentKey];
          const blob = new Blob([fileContent], {
            type: "text/plain",
          });
          const file = new File([blob], _nFileName, {
            type: "text/plain",
          });
          if (fileMap[fileName]) {
            fileUpload.value[fileMap[fileName]] = file;
            switch (fileName) {
              case "AI_change文件_n":
                configForm.value.property5 =
                  fileUpload.value.AI_change文件.name;
                break;
              case "AI_fixed文件_n":
                configForm.value.property4 = fileUpload.value.AI_fixed文件.name;
                break;
              case "温度mod默认文件_n":
                configForm.value.property3 =
                  fileUpload.value.温度mod默认文件.name;
                break;
              case "电路结构netlist文件_n":
                configForm.value.property2 =
                  fileUpload.value.电路结构netlist文件.name;
                break;
              case "蒙特卡洛AI_change文件_n":
                configForm.value.property11 =
                  fileUpload.value.蒙特卡洛AI_change文件.name;
                break;
              case "蒙特卡洛AI_fixed文件_n":
                configForm.value.property10 =
                  fileUpload.value.蒙特卡洛AI_fixed文件.name;
                break;
              case "蒙特卡洛sp文件_n":
                configForm.value.property9 =
                  fileUpload.value.蒙特卡洛sp文件.name;
                break;
              case "默认sp文件_n":
                configForm.value.property1 = fileUpload.value.默认sp文件.name;
                break;
              case "温度mod文件1_n":
                configForm.value.property6 = fileUpload.value.温度mod文件1.name;
                break;
              case "温度mod文件2_n":
                configForm.value.property7 = fileUpload.value.温度mod文件2.name;
                break;
              case "ra文件_n":
                configForm.value.property8 = fileUpload.value.ra文件.name;
                break;
              case "蒙特卡洛ra文件_n":
                configForm.value.property12 =
                  fileUpload.value.蒙特卡洛ra文件.name;
                break;
              default:
                console.log(`Unknown file: ${fileName}`);
            }
          } else {
            console.log(`Unknown file: ${fileName}`);
          }
        } else {
          console.error(`Content for file ${fileName} not found`);
        }
      }
    }
    console.log(fileUpload.value);
  } catch (e) {
    console.error("e:",e)
    ElMessage.info("请上传文件");
  }
};
const configForm = ref({
  circuit: route.params.circuitName,
  property1: "",
  property2: "",
  property3: "",
  property4: "",
  property5: "",
  property6: "",
  property7: "",
  property8: "",
  property9: "",
  property10: "",
  property11: "",
  property12: "",
});
const configFormzh_CN = ref({
  电路名称: route.params.circuitName,
  默认sp文件: "",
  电路结构netlist文件: "",
  温度mod默认文件: "",
  AI_fixed文件: "",
  AI_change文件: "",
  温度mod文件1: "",
  温度mod文件2: "",
  ra文件: "",
  蒙特卡洛sp文件: "",
  蒙特卡洛AI_fixed文件: "",
  蒙特卡洛AI_change文件: "",
  蒙特卡洛ra文件: "",
});
const rules = {
  fileNameSp: [
    {
      required: true,
      message: "请上传基础仿真sp文件",
      trigger: "change",
    },
  ],
  property1: [
    {
      required: true,
      message: "请上传默认sp文件",
      trigger: "change",
    },
  ],
  property2: [
    {
      required: true,
      message: "请上传电路结构netlist文件",
      trigger: "change",
    },
  ],
  property3: [
    {
      required: true,
      message: "请上传温度mod默认文件",
      trigger: "change",
    },
  ],
  property4: [
    {
      required: true,
      message: "请上传AI_fixed文件",
      trigger: "change",
    },
  ],
  property5: [
    {
      required: true,
      message: "请上传AI_change文件",
      trigger: "change",
    },
  ],
};
const fileUpload = ref({});


// 上传配置
async function uploadConfig() {
  if (
    configForm.value.property1 == "" ||
    configForm.value.property2 == "" ||
    configForm.value.property3 == "" ||
    configForm.value.property4 == "" ||
    configForm.value.property5 == ""
  ) {
    ElMessage.warning("操作失败");
    confirm("有必须上传的文件未上传");
  } else {
    try {
      const formData = new FormData();
      if (
        fileUpload.value.property1 != null ||
        fileUpload.value.property2 != null ||
        fileUpload.value.property3 != null ||
        fileUpload.value.property4 != null ||
        fileUpload.value.property5 != null ||
        fileUpload.value.property6 != null ||
        fileUpload.value.property7 != null ||
        fileUpload.value.property8 != null ||
        fileUpload.value.property9 != null ||
        fileUpload.value.property10 != null ||
        fileUpload.value.property11 != null ||
        fileUpload.value.property12 != null
      ) {
        formData.append("电路名称", configFormzh_CN.value.电路名称);
        formData.append(
          "默认sp文件",
          fileUpload.value.property1 ? fileUpload.value.property1.raw : null
        );
        formData.append(
          "电路结构netlist文件",
          fileUpload.value.property2 ? fileUpload.value.property2.raw : null
        );
        formData.append(
          "温度mod默认文件",
          fileUpload.value.property3 ? fileUpload.value.property3.raw : null
        );
        formData.append(
          "AI_fixed文件",
          fileUpload.value.property4 ? fileUpload.value.property4.raw : null
        );
        formData.append(
          "AI_change文件",
          fileUpload.value.property5 ? fileUpload.value.property5.raw : null
        );
        formData.append(
          "温度mod文件1",
          fileUpload.value.property6 ? fileUpload.value.property6.raw : null
        );
        formData.append(
          "温度mod文件2",
          fileUpload.value.property7 ? fileUpload.value.property7.raw : null
        );
        formData.append(
          "ra文件",
          fileUpload.value.property8 ? fileUpload.value.property8.raw : null
        );
        formData.append(
          "蒙特卡洛sp文件",
          fileUpload.value.property9 ? fileUpload.value.property9.raw : null
        );
        formData.append(
          "蒙特卡洛AI_fixed文件",
          fileUpload.value.property10 ? fileUpload.value.property10.raw : null
        );
        formData.append(
          "蒙特卡洛AI_change文件",
          fileUpload.value.property11 ? fileUpload.value.property11.raw : null
        );
        formData.append(
          "蒙特卡洛ra文件",
          fileUpload.value.property12 ? fileUpload.value.property12.raw : null
        );
      } else {
        formData.append("电路名称", configFormzh_CN.value.电路名称);
        formData.append(
          "默认sp文件",
          fileUpload.value.默认sp文件 ? fileUpload.value.默认sp文件 : null
        );
        formData.append(
          "电路结构netlist文件",
          fileUpload.value.电路结构netlist文件
            ? fileUpload.value.电路结构netlist文件
            : null
        );
        formData.append(
          "温度mod默认文件",
          fileUpload.value.温度mod默认文件
            ? fileUpload.value.温度mod默认文件
            : null
        );
        formData.append(
          "AI_fixed文件",
          fileUpload.value.AI_fixed文件 ? fileUpload.value.AI_fixed文件 : null
        );
        formData.append(
          "AI_change文件",
          fileUpload.value.AI_change文件 ? fileUpload.value.AI_change文件 : null
        );
        formData.append(
          "温度mod文件1",
          fileUpload.value.温度mod文件1 ? fileUpload.value.温度mod文件1 : null
        );
        formData.append(
          "温度mod文件2",
          fileUpload.value.温度mod文件2 ? fileUpload.value.温度mod文件2 : null
        );
        formData.append(
          "ra文件",
          fileUpload.value.ra文件 ? fileUpload.value.ra文件 : null
        );
        formData.append(
          "蒙特卡洛sp文件",
          fileUpload.value.蒙特卡洛sp文件
            ? fileUpload.value.蒙特卡洛sp文件
            : null
        );
        formData.append(
          "蒙特卡洛AI_fixed文件",
          fileUpload.value.蒙特卡洛AI_fixed文件
            ? fileUpload.value.蒙特卡洛AI_fixed文件
            : null
        );
        formData.append(
          "蒙特卡洛AI_change文件",
          fileUpload.value.蒙特卡洛AI_change文件
            ? fileUpload.value.蒙特卡洛AI_change文件
            : null
        );
        formData.append(
          "蒙特卡洛ra文件",
          fileUpload.value.蒙特卡洛ra文件
            ? fileUpload.value.蒙特卡洛ra文件
            : null
        );
      }

      console.log("formData:", formData);
      console.log("configFormzh_CN:", configFormzh_CN);
      console.log("fileUpload.value:", fileUpload.value);
      await huada_config_upload(formData);
      ElMessage.success("上传成功");
    } catch (e) {
      confirm("上传失败，请确认是否遗漏文件或存在演算结果");
      try {
        router.push("/index/iIndex");
      } catch (error) {
        router.push("/index/iIndex");
      }
      ElMessage.warning("上传失败，当前电路可能存在演算结果");
    }
  }
}

const showDialog = ref(false); // 控制弹窗显示隐藏
const form = ref({
  old_circuit_diagram_name: "",
  new_circuit_diagram_name: "",
});
const submitForm = async () => {
  if (form.value.new_circuit_diagram_name.trim() === "") {
    ElMessage.error("新电路名不能为空");
    return;
  }
  try {
    await reCircuitName(form.value);
    circuitName.value = form.value.new_circuit_diagram_name;
    showDialog.value = false; // 关闭弹窗
    ElMessage.success("电路名修改成功");
    router.push({
      name: "电路配置",
      params: {
        circuitName: circuitName.value,
      },
    });
  } catch (e) {
    showDialog.value = false;
    confirm("修改失败，电路可能存在仿真结果或电路名重复");
  }
};
onMounted(() => {
  circuitName.value = route.params.circuitName;
  console.log(circuitName.value);
  form.value.old_circuit_diagram_name = circuitName.value;
  getUploadFile();
});
</script>

<style>
.inputStyles {
  width: 850px;
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}
</style>
